package com.time.social.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.google.gson.Gson;
import com.time.auth.api.UserFeignService;
import com.time.auth.entity.AuthUserDTO;
import com.time.auth.entity.Result;
import com.time.social.api.UserFeignServiceExt;
import com.time.social.entity.SocialUserInfo;
import com.time.social.service.AuthUserRpcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务RPC实现类
 *
 * @author: HuangQi
 * @date: Created in 2025/01/XX
 * @description: 用户服务RPC实现类
 */
@Slf4j
@Service
public class AuthUserRpcServiceImpl implements AuthUserRpcService {

    @Autowired(required = false)
    private UserFeignService userFeignService;

    @Autowired(required = false)
    private UserFeignServiceExt userFeignServiceExt;

    private final Gson gson = new Gson();

    @Override
    public String createOrUpdateUser(SocialUserInfo socialUserInfo) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AuthUserRpcServiceImpl.createOrUpdateUser.socialUserInfo:{}", socialUserInfo);
            }

            // 生成用户名：使用社交平台类型 + openId
            String userName = socialUserInfo.getSocialType().toLowerCase() + "_" + socialUserInfo.getOpenId();

            // 构建用户信息
            AuthUserDTO authUserDTO = new AuthUserDTO();
            authUserDTO.setUserName(userName);
            authUserDTO.setEmail(socialUserInfo.getEmail());
            authUserDTO.setAvatarUrl(socialUserInfo.getAvatar());
            authUserDTO.setAboutMe(socialUserInfo.getNickname());

            // 将社交平台信息存入extJson
            Map<String, Object> extData = new HashMap<>();
            extData.put("socialType", socialUserInfo.getSocialType());
            extData.put("openId", socialUserInfo.getOpenId());
            extData.put("unionId", socialUserInfo.getUnionId());
            extData.put("nickname", socialUserInfo.getNickname());
            extData.put("rawData", socialUserInfo.getRawData());
            authUserDTO.setExtJson(gson.toJson(extData));

            // 检查用户是否存在
            if (userFeignService != null) {
                AuthUserDTO queryDTO = new AuthUserDTO();
                queryDTO.setUserName(userName);
                Result<AuthUserDTO> queryResult = userFeignService.getUserInfo(queryDTO);

                if (queryResult != null && queryResult.getSuccess() && queryResult.getData() != null 
                    && queryResult.getData().getUserId() != null) {
                    // 用户已存在，更新用户信息
                    authUserDTO.setUserId(queryResult.getData().getUserId());
                    log.info("用户已存在，用户ID: {}", authUserDTO.getUserId());
                    
                    // 更新用户信息
                    if (userFeignServiceExt != null) {
                        Result<Boolean> updateResult = userFeignServiceExt.update(authUserDTO);
                        if (updateResult != null && updateResult.getSuccess()) {
                            log.info("用户信息更新成功: {}", userName);
                        } else {
                            log.warn("用户信息更新失败: {}", userName);
                        }
                    }
                } else {
                    // 用户不存在，注册新用户
                    log.info("用户不存在，需要注册新用户: {}", userName);
                    
                    // 注册新用户
                    if (userFeignServiceExt != null) {
                        Result<Boolean> registerResult = userFeignServiceExt.register(authUserDTO);
                        if (registerResult != null && registerResult.getSuccess()) {
                            log.info("用户注册成功: {}", userName);
                        } else {
                            log.warn("用户注册失败: {}", userName);
                        }
                    } else {
                        log.warn("UserFeignServiceExt未配置，无法注册用户");
                    }
                }
            } else {
                log.warn("UserFeignService未配置，无法调用auth模块服务");
            }

            return userName;
        } catch (Exception e) {
            log.error("AuthUserRpcServiceImpl.createOrUpdateUser.error:{}", e.getMessage(), e);
            throw new RuntimeException("创建或更新用户失败", e);
        }
    }

    @Override
    public Object doLogin(String userName) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AuthUserRpcServiceImpl.doLogin.userName:{}", userName);
            }

            // 使用Sa-Token进行登录
            // 格式：user_用户名（与auth模块保持一致）
            String loginId = "user_" + userName;
            StpUtil.login(loginId);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            
            log.info("用户登录成功: {}, tokenInfo: {}", userName, tokenInfo);
            return tokenInfo;
        } catch (Exception e) {
            log.error("AuthUserRpcServiceImpl.doLogin.error:{}", e.getMessage(), e);
            throw new RuntimeException("用户登录失败", e);
        }
    }
}

